<style scoped>
    .config_main{
        padding:20px;
        background: #fff;
    }
    .config_main .row-col{
        display: flex;
        flex-direction: row;
        align-items: center;
    }
    .config_main .block{
        display: flex;
        flex-direction: row;
        align-items: center;
        flex-wrap: wrap;
    }
    .config_main .block .left{
        width:150px;
        color:#999;
    }
    .config_main .block .right{
        display: flex;
        flex-direction: row;
        align-items: center;
    }
    .config_main .block .inp1{
        width:380px;
    }
    .config_main .block .inp2{
        width:300px;
    }
    .config_main .block .textarea{
        width:800px;
    }
    .config_main .btns_submit{
        padding:50px 0 100px 0;
        display: flex;
        flex-direction: row;
        align-items: center;
    }
    .lable_parent{
        position: relative;
    }
    .lable_parent .delete{
        position: absolute;
        right:20px;
        top:0;
    }
</style>
<div class="content" id="team" v-cloak>
    <el-row>
        <el-col :span="12">
            <div class="grid-content bg-purple com_title">应用构建配置</div>
        </el-col>
    </el-row>
    <div class="config_main mt30">
        <div class="block mb50">
            <div class="bottom">
                <div class="top mb20">资产列表</div>
                <div class="mb10">
                    <el-button @click="serverConfigs()" type="primary" icon="el-icon-tickets" size="medium">脚本任务</el-button>
                    <el-button @click="applicationConsole()" type="danger" icon="el-icon-s-tools" size="medium">控制台</el-button>
                    <span class="ml10 light"><i class="el-icon-warning fs-16 mr5 primary"></i>默认执行所有资产项操作，若有选择则执行选中资产项的相关操作(例如：部署、生成构建配置等操作)。
                    </span>
                </div>
                <el-table 
                    :data="assetslist" 
                    ref="multipleTable" 
                    border 
                    @selection-change="handleSelectionChange" 
                    style="width:1000px;font-size:12px;">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column prop="name" label="资产名称" width="200">
                    </el-table-column>
                    <el-table-column prop="outer_ip" label="外网IP" width="200">
                    </el-table-column>
                    <el-table-column prop="lan_ip" label="内网IP" width="200">
                    </el-table-column>
                    <el-table-column prop="user" label="用户名" width="150">
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <div>
                                <el-button @click="serverConfigs(scope.row)" type="primary" size="mini" plain>脚本任务</el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
        <div class="block mb50">
            <el-button type="primary" icon="el-icon-plus" @click="addNewTask" class="ml30">新建任务</el-button>
        </div>
        <el-tabs 
            v-model="editableTabsValue" 
            closable 
            type="border-card"
            v-if="tasklist.length" 
            @tab-remove="removeTab">
            <el-tab-pane 
                class="lable_parent" 
                v-for="(item,index) in tasklist" 
                :key="index" 
                :label="item.task_name" 
                :name="index+''">
                <div class="delete">
                    <el-button type="danger" icon="el-icon-delete" size="medium" @click="deleteItemTask(item,index)" class="ml30">删除此任务</el-button>
                </div>
                <div class="block mt30">
                    <div class="left">任务名称<span class="red">*</span></div>
                    <div class="right">
                        <el-input v-model="item.task_name" class="inp1"></el-input>
                    </div>
                </div>
                <div class="block mt30">
                    <div class="left">任务类型<span class="red">*</span></div>
                    <div class="right">
                        {{item.task_type=='git'?'git hooks任务':''}}
                        {{item.task_type=='shell'?'shell脚本任务':''}}
                        {{item.task_type=='command'?'命令行运行任务':''}}
                    </div>
                </div>
                <div v-show="item.task_type!='command'?true:false">
                    <div v-show="item.task_type=='git'?true:false">
                        <div class="block mt30">
                            <div class="left">选择git部署方式<span class="red">*</span></div>
                            <div class="right">
                                <el-button :type="item.git_type=='https'?'primary':'default'" size="small" @click="selectGitType(index,item,'https')" round>https方式
                                </el-button>
                                <el-button :type="item.git_type=='ssh'?'primary':'default'" size="small" @click="selectGitType(index,item,'ssh')" class="ml30" round>
                                    ssh方式</el-button>
                            </div>
                        </div>
                        <div class="block mt30">
                            <div class="left"></div>
                            <div class="right light">
                                <span v-if="item.git_type=='https'?true:false">
                                    <i class="el-icon-warning fs-16 mr5 primary"></i>
                                    使用https方式拉取代码时需要用户名和密码，若用户名中有<span class="red">@</span>时需要转换为<span class="red">%40</span>。
                                </span>
                                <span v-if="item.git_type=='ssh'?true:false">
                                    <i class="el-icon-warning fs-16 mr5 primary"></i>
                                    使用ssh方式拉取代码时请确认git端项目已填写ssh key秘钥。
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="block mt30">
                        <div class="left">部署shell脚本路径<span class="red">*</span></div>
                        <div class="right">
                            <el-input v-model="item.shell_path" class="inp1" placeholder="例如：/usr/src/sh/build.sh"></el-input>
                            <span class="ml20 light">备注：若目录或文件不存在则自动创建。</span>
                        </div>
                    </div>
                    <div class="block mt30">
                        <div class="left">shell脚本参数</div>
                        <div class="right">
                            <el-input v-model="item.shell_opction" class="inp1" placeholder="shell脚本参数请以空格隔开"></el-input>
                        </div>
                    </div>
                    <div class="block mt30">
                        <div class="left">shell脚本写入方式<span class="red">*</span></div>
                        <div class="right">
                            <el-select v-model="item.shell_write_type" class="inp1" placeholder="请选择">
                                <el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>
                        </div>
                    </div>
                    <div class="block mt30">
                        <div class="left">发布前是否先做备份</div>
                        <div class="right">
                            <el-switch v-model="item.is_backups"></el-switch>
                        </div>
                    </div>
                    <div class="row-col mt30">
                        <div class="block">
                            <div class="left">需要备份的资源<span class="red">*</span></div>
                            <div class="right">
                                <el-input v-model="item.project_path" class="inp2" placeholder="备份目标可以是文件夹也可以是一个文件"></el-input>
                            </div>
                        </div>
                        <div class="block ml20">
                            <div class="left">备份文件存放位置<span class="red">*</span></div>
                            <div class="right">
                                <el-input v-model="item.backups_path" class="inp2" placeholder="备份文件存储的位置"></el-input>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="block mt30">
                    <div class="left">{{item.task_type=='command'?'命令行脚本内容':'部署shell脚本'}}<span class="red">*</span></div>
                    <div>
                        <div class="mt10 right">
                            <div :id="'editor_'+index" :style="{width:'1000px',height:item.task_type=='command'?'60px':'350px'}"></div>
                        </div>
                        <div class="mt10 light" v-show="item.task_type!='command'?true:false">备注：服务器初始shell脚本。</div>
                    </div>
                </div>
                <div class="block mt30">
                    <div class="left">备注</div>
                    <div class="right">
                        <el-input type="textarea" :rows="2" placeholder="选填" v-model="item.remarks" style="width:1000px;">
                        </el-input>
                    </div>
                </div>
            </el-tab-pane>
        </el-tabs>
        <div class="btns_submit" v-if="tasklist.length">
            <el-button type="primary" @click="submitConfigs" class="mb20">保存构建配置</el-button>
            <el-button type="danger" @click="goToBuild" class="mb20" plain>去发布应用</el-button>
            <el-button type="default" @click="goBack" class="mb20">取消</el-button>
        </div>
        
        <!-- 新建任务model -->
        <el-dialog width="600px" title="新建任务" :visible.sync="dialogTableVisible">
            <div class="com_model_main">
                <div class="com_model_block">
                    <div class="left">任务名称</div>
                    <el-input class="inp" v-model.trim="task_name" placeholder="请输入任务名称"></el-input>
                </div>
                <div class="com_model_block">
                    <div class="left">任务类型</div>
                    <el-select class="inp" v-model="task_type" placeholder="请选择">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>
                </div>
                <div class="btns">
                    <el-button type="primary" @click="submitTask"> 提交 </el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</div>
<script>var require = { paths: { 'vs': 'https://cdn.bootcss.com/monaco-editor/0.16.2/min/vs' } };</script>
<script src="//cdn.bootcss.com/monaco-editor/0.16.2/min/vs/loader.js"></script>
<script>
    const monacos = {};
    new Vue({
        el: '#team',
        data: function () {
            return {
                id: util.getQueryString('id'),
                details:{},
                assetslist:[],
                dialogTableVisible:false,
                options:[{
                    value: 'git',
                    label: 'GIT任务'
                },{
                    value: 'shell',
                    label: 'SHELL任务'
                }, {
                    value: 'command',
                    label: '命令行运行任务'
                }],
                options1: [{
                    value: 1,
                    label: '新建文件并上传方式'
                }, {
                    value: 2,
                    label: 'shell窗口命令行创建方式'
                }],
                task_name:'',
                task_type: '',
                tasklist:[],
                editableTabsValue: util.getQueryString('tab') || '0',
                multipleSelection:[],
            }
        },
        mounted() {
            this.itemdetail();
        },
        methods: {
            runMonaco(id,data,type) {
                const moId = `editor_${id}`;
                if(type) {
                    monacos[moId].setValue(data);
                    return;
                }
                //载入Monaco
                let editor = null;
                _this = this;
                require(['vs/editor/editor.main'], function () {
                    //得到支持的语言
                    var modesIds = monaco.languages.getLanguages().map(function (lang) { return lang.id }).sort();
                    //创建编辑器
                    monacos[moId] = editor = monaco.editor.create(document.getElementById(moId), {
                        value: data,
                        language: 'shell',
                        scrollBeyondLastLine: false,
                        automaticLayout: true,
                        fontSize:14,
                        //主题，三款：vs、vs-dark、hc-black
                        theme: 'vs-dark',
                        minimap: {
                            enabled: false
                        }
                    });
                    editor.onDidChangeModelContent(function (e) {
                        _this.tasklist[id].shell_body = editor.getValue()
                    });
                });
            },
            itemdetail(type=false){
                util.ajax({
                    type: 'get',
                    url: `${config.baseApi}api/v1/application/itemdetail`,
                    data: {
                        id: this.id,
                    },
                    success: data => {
                        this.details = data.data;
                        this.assetslist = data.data.assets_list || [];
                        const tasklist = data.data.task_list || [];
                        if (tasklist && tasklist.length) {
                            tasklist.forEach((item, index) => {
                                item.shell_write_type = item.shell_write_type ? parseInt(item.shell_write_type) : 1;
                                item.is_backups = item.is_backups == 1 ? true : false;
                                if(!item.shell_body) item.shell_body = '#!/bin/bash\r\n'
                                this.runMonaco(index, item.shell_body, type)
                            })
                        }
                        this.tasklist = tasklist;
                        setTimeout(()=>{ this.assetslist.forEach(item => {this.$refs.multipleTable.toggleRowSelection(item, true);})})
                    }
                })
            },
            selectGitType(index,item,type){
                item.git_type = type;
                const https = 'git clone https://xxx%40qq.com:123456@git.xxx.com/www.git'
                const ssh = 'git clone git@git.xxx.com/www.git'
                if(type === 'https'){
                    if(item.shell_body.indexOf(ssh) > -1){
                        item.shell_body = item.shell_body.replace(ssh, https)
                    }else if (item.shell_body.indexOf(https) == -1) {
                        item.shell_body = item.shell_body + '\r\n' + https + '\r\n'
                    }
                }else if(type === 'ssh'){
                    if (item.shell_body.indexOf(https) > -1) {
                        item.shell_body = item.shell_body.replace(https, ssh)
                    }else if (item.shell_body.indexOf(ssh) == -1) {
                        item.shell_body =  item.shell_body + '\r\n' +ssh + '\r\n'
                    }
                }
                monacos[`editor_${index}`].setValue(item.shell_body);
            },
            addNewTask(){
                this.task_type = '';
                this.task_name = '';
                this.dialogTableVisible = true;
            },
            submitTask(){
                if(!this.task_name){
                    popup.alert({title:'请填写任务名称!'})
                    return;
                }
                if (!this.task_type) {
                    popup.alert({ title: '请选择任务类型!' })
                    return;
                }
                this.dialogTableVisible = false;
                this.editableTabsValue = this.tasklist.length + '';
                let default_shell_body = '';
                if(this.task_type === 'git'){
                    default_shell_body = '#!/bin/bash\r\ngit clone https://xxx%40qq.com:123456@git.xxx.com/www.git\r\n'
                } else if(this.task_type === 'shell'){
                    default_shell_body = '#!/bin/bash\r\n';
                }

                this.tasklist.push({
                    task_name:this.task_name,
                    task_type: this.task_type,
                    shell_body: default_shell_body,
                    git_type:'https',
                    is_backups:false,
                })
                setTimeout(()=>{ this.runMonaco(this.tasklist.length - 1, default_shell_body) },0)
            },
            removeTab(targetName){
                popup.confirm({title: `确定删除此任务吗？`, yes: () => {
                    let tabs = this.tasklist;
                    let activeName = this.editableTabsValue;
                    activeName = tabs[targetName + 1]? targetName: activeName - 1;
                    this.editableTabsValue = activeName + '';
                    this.tasklist = tabs.filter((tab,index) => index != targetName);
                }})
            },
            deleteItemTask(item,index){
                popup.confirm({ title: `确定删除${item.task_name}任务吗？`, yes: () => {
                    this.editableTabsValue = '0';
                    this.tasklist.splice(index, 1);
                }})
            },
            goBack(){
                location.href="/application"
            },
            submitConfigs(){
                this.tasklist.forEach((item,index)=>{
                    item.is_backups = item.is_backups ? 1 : 0;
                    item.shell_body = monacos[`editor_${index}`].getValue() || '#!/bin/bash\r\n';
                    if(item.shell_body.indexOf('SUCCESSFUL_COMMAND_CONSTRUCTION') == -1 && item.task_type != 'command') {
                        item.shell_body = item.shell_body + '\r\n#以下内容由系统默认增加,放置于最后,不要做任何修改,用于判断shell是否执行成功\r\nif [ $? -eq 0 ]\r\nthen\r\n    echo "SUCCESSFUL_COMMAND_CONSTRUCTION"\r\nelse\r\n    echo "ERROR_COMMAND_CONSTRUCTION"\r\nfi'
                    }
                })
                util.ajax({
                    url: `${config.baseApi}api/v1/application/updateConfigs`,
                    data: {
                        id:this.id,
                        tasklist:this.tasklist,
                    },
                    success: data => {
                        this.itemdetail(true);
                        popup.miss({title:'操作成功!'})
                    }
                })
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            serverConfigs(item) {
                if (!item && !this.multipleSelection.length) {
                    popup.alert({ title: '请选择需要配置的资产!' })
                    return;
                }
                const assestsList = item ? [item] : this.multipleSelection;
                util.setStorage('session', 'assets_list_configs', JSON.stringify(assestsList));
                location.href = "/assetsconfig";
            },
            goToBuild(){
                location.href = "/buildprocess?id="+this.id;
            },
            applicationConsole() {
                if (!this.multipleSelection.length) {
                    popup.alert({ title: '请选择进入控制台的资产列表!' })
                    return;
                }
                let ids = '';
                this.multipleSelection && this.multipleSelection.forEach(item => {
                    ids = ids + item._id + ','
                })
                ids = ids ? ids.slice(0, -1) : '';
                window.open("/console?ids=" + ids);
            },
        }
    })
</script>